package reduce.fz.com.reduce.fragment;


import android.content.Intent;
import android.os.Bundle;
import android.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.TypeReference;

import java.util.List;

import de.greenrobot.event.EventBus;
import reduce.fz.com.reduce.R;
import reduce.fz.com.reduce.abstracts.AbResponseListener;
import reduce.fz.com.reduce.activity.AttentionListActivity;
import reduce.fz.com.reduce.activity.MessageCenterActivity;
import reduce.fz.com.reduce.activity.MySocietyListActivity;
import reduce.fz.com.reduce.activity.MyWorksListActivity;
import reduce.fz.com.reduce.activity.VideoCardDetailActivity;
import reduce.fz.com.reduce.adapter.BaseRecycleViewHolder;
import reduce.fz.com.reduce.bean.MessageNotice;
import reduce.fz.com.reduce.bean.ServiceException;
import reduce.fz.com.reduce.bean.User;
import reduce.fz.com.reduce.bean.VideoCard;
import reduce.fz.com.reduce.bean.page.Pagination;
import reduce.fz.com.reduce.bean.result.Result;
import reduce.fz.com.reduce.custom.DetailUserFollowView;
import reduce.fz.com.reduce.custom.NetworkImageView;
import reduce.fz.com.reduce.custom.view.RoundNetworkBorderImageView;
import reduce.fz.com.reduce.fragment.base.BaseListHeaderFragment;
import reduce.fz.com.reduce.service.UserService;
import reduce.fz.com.reduce.service.preference.UserPreference;
import reduce.fz.com.reduce.util.ApiUtil;
import reduce.fz.com.reduce.util.HttpUtils;
import reduce.fz.com.reduce.util.ScreenUtils;
import reduce.fz.com.reduce.util.ServiceBuilder;

/**
 * A simple {@link Fragment} subclass.
 */
public class UserDetailFragment2 extends BaseListHeaderFragment<BaseRecycleViewHolder, VideoCard, User> implements FragmentCacheSupport {
    private User user = null;
    private Long uid = 0l;
    private UserDetailHeaderViewHolder headerViewHolder = null;
    private UserService userService = ServiceBuilder.builderUserService(null);

    public static UserDetailFragment2 create(Long uid) {
        UserDetailFragment2 fragment = new UserDetailFragment2();
        Bundle bundle = new Bundle();
        bundle.putSerializable("uid", uid);
        fragment.setArguments(bundle);
        return fragment;
    }


    @Override
    public int getSpanSize() {
        return 3;
    }

    public void loadUser() {
        userService.getUser(uid, new AbResponseListener<User>(new TypeReference<Result<User>>() {
        }) {
            @Override
            public void error(ServiceException e) {

            }

            @Override
            public void responseInfo(Result<User> data) {
                user = data.getData();
                addHeader(user);

            }
        });
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        uid = getArguments().getLong("uid");

        EventBus.getDefault().register(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    /**
     * 当有新消息时点亮小红点
     *
     * @param notice
     */
    public void onEvent(MessageNotice notice) {
        headerViewHolder.displayMessagePoint(true);
    }

    @Override
    public String getCacheName() {
        return "USER_DETAIL_FRAGMENT2";
    }

    @Override
    public String getFragmentTitle() {
        return "个人详情";
    }

    public interface UserDetailHeaderListener {
        //消息中心点击
        public void messageClick();

        //我的社团点击
        public void mysocietyClick();

        //我的作品点击
        public void myworkClick();

        //我的关注点击
        public void myFollowClick();

        //我的粉丝点击
        public void myFensiClick();
    }


    public UserDetailFragment2() {
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        loadUser();


    }

    @Override
    public LinearLayoutManager getLayoutManager() {
        GridLayoutManager layoutManager = new GridLayoutManager(getActivity(), 3);
        return layoutManager;
    }


    @Override
    public void request(String url) {
        HttpUtils.get(url, new AbResponseListener<List<VideoCard>>(new TypeReference<Result<List<VideoCard>>>() {
        }) {
            @Override
            public void error(ServiceException e) {
                loadingDialog.dismiss();
            }

            @Override
            public void responseInfo(Result<List<VideoCard>> data) {
                addResult(data);
            }
        });
    }

    /**
     * 跳转到视频卡片详情
     *
     * @param cardid
     */
    public void forwardDetail(Long cardid) {
        Intent intent = new Intent(this.getActivity(), VideoCardDetailActivity.class);
        intent.putExtra("cardid", cardid);
        startActivity(intent);
    }

    public void forwardMyWorks() {
        Intent intent = new Intent(this.getActivity(), MyWorksListActivity.class);
        intent.putExtra("uid",uid);
        startActivity(intent);
    }

    @Override
    protected UserDetailHeaderViewHolder createHeaderViewHolder(ViewGroup parent) {
        View view = layoutInflater.inflate(R.layout.view_user_detail_header, parent, false);
        UserDetailHeaderViewHolder holder = new UserDetailHeaderViewHolder(view, new UserDetailHeaderListener() {
            @Override
            public void messageClick() {
                //跳转到我的消息页面
                forwardMyMessage();

            }

            @Override
            public void mysocietyClick() {
                //跳转到我的社团页面
                forwardMySociety();

            }

            @Override
            public void myworkClick() {
                //跳转到我的作品页面
                forwardMyWorks();

            }

            @Override
            public void myFollowClick() {
                //跳转到我的关注页面
                forwardFollow();

            }

            @Override
            public void myFensiClick() {
                //跳转到我的粉丝页面
                forwardFensi();

            }
        });
        return holder;
    }


    @Override
    protected SocietyUserDynamicViewHolder createItemViewHolder(ViewGroup parent) {
        View view = layoutInflater.inflate(R.layout.view_user_detail_card, parent, false);
        SocietyUserDynamicViewHolder viewHolder = new SocietyUserDynamicViewHolder(view, new DetailVideoListener() {
            @Override
            public void videoCardClick(VideoCard card) {
                forwardDetail(card.cardid);
            }
        });
        return viewHolder;
    }

    @Override
    protected SocietyUserDynamicViewHolder createfootViewHolder(View view) {
        return new SocietyUserDynamicViewHolder(view);
    }

    @Override
    protected String setUrlBeforeRequest(List<VideoCard> datas, Pagination pagination) {
        String url = ApiUtil.getApi(context, R.array.api_my_video_card, uid, pagination.getPageNo(), pagination.getPageSize());
        return url;
    }

    @Override
    protected int getPageType() {
        return 0;
    }

    /**
     * 头部
     */
    public static class UserDetailHeaderViewHolder extends BaseRecycleViewHolder<User> implements View.OnClickListener {
        //头像
        private RoundNetworkBorderImageView mAtavar;
        //昵称
        private TextView mNickName;
        //性别
        private ImageView mSex;
        //年龄
        private TextView mAge;
        //个人介绍
        private TextView mIntr;
        //作品
        private TextView mWorkCount;
        //关注
        private TextView mFollowCount;
        //粉丝数量
        private TextView mFensiCount;
        private UserDetailHeaderListener listener;
        private TextView mMessage;
        private TextView mMySociety;
        private DetailUserFollowView mFollow;

        private RelativeLayout mRlMessage;
        private RelativeLayout mRlFollow;
        private RelativeLayout mRlSociety;
        private LinearLayout mLlWorks;
        private LinearLayout mLlFollow;
        private LinearLayout mLlFensi;


        //
        private View itemView;

        public void initWidget(View itemView) {
            mLlWorks = (LinearLayout) itemView.findViewById(R.id.ll_works);
            mLlFollow = (LinearLayout) itemView.findViewById(R.id.ll_follow);
            mLlFensi = (LinearLayout) itemView.findViewById(R.id.ll_fensi);
            mAtavar = (RoundNetworkBorderImageView) itemView.findViewById(R.id.iv_user_avatar);
            mNickName = (TextView) itemView.findViewById(R.id.tv_user_nickname);
            mSex = (ImageView) itemView.findViewById(R.id.iv_sex);
            mAge = (TextView) itemView.findViewById(R.id.tv_age);
            mIntr = (TextView) itemView.findViewById(R.id.tv_intr);
            mWorkCount = (TextView) itemView.findViewById(R.id.tv_works_count);
            mFollowCount = (TextView) itemView.findViewById(R.id.tv_follow_count);
            mFensiCount = (TextView) itemView.findViewById(R.id.tv_fensi_count);
            mMessage = (TextView) itemView.findViewById(R.id.tv_message);
            mMySociety = (TextView) itemView.findViewById(R.id.tv_mysociety);
            mFollow = (DetailUserFollowView) itemView.findViewById(R.id.dfv_follow);
            mRlMessage = (RelativeLayout) itemView.findViewById(R.id.rl_message);
            mRlFollow = (RelativeLayout) itemView.findViewById(R.id.rl_follow);
            mRlSociety = (RelativeLayout) itemView.findViewById(R.id.rl_society);
        }

        public void dealDisplay(User user) {
            User me = UserPreference.getUser();
            if (((long) me.uid) == ((long) user.uid)) {
                mRlMessage.setVisibility(View.VISIBLE);
                mRlFollow.setVisibility(View.GONE);
            } else {
                mRlMessage.setVisibility(View.GONE);
                mRlFollow.setVisibility(View.VISIBLE);
            }

        }


        public UserDetailHeaderViewHolder(View itemView, UserDetailHeaderListener listener) {
            this(itemView);
            this.listener = listener;
        }

        public UserDetailHeaderViewHolder(View itemView) {
            super(itemView);
            initWidget(itemView);
        }

        @Override
        public void renderView(User data, int position) {
            mFollow.setOnClickListener(this);
            mWorkCount.setOnClickListener(this);
            mFollowCount.setOnClickListener(this);
            mFensiCount.setOnClickListener(this);
            mMessage.setOnClickListener(this);
            mMySociety.setOnClickListener(this);
            mLlWorks.setOnClickListener(this);
            mLlFensi.setOnClickListener(this);
            mLlFollow.setOnClickListener(this);
            dealDisplay(data);
            mAtavar.setImageUrl(data.avatar, HttpUtils.getAvatarImageLoader());
            mNickName.setText(data.nickname);
            mSex.setImageResource((data.sex).equals("M") ? R.drawable.detail_male : R.drawable.detail_female);
            mAge.setText(data.age == 0 ? "0岁" : data.age + "岁");
            // mIntr.setText(data.intr);
            mWorkCount.setText(data.userAttach.works_num + "");
            mFollowCount.setText(data.userAttach.follow_num + "");
            mFensiCount.setText(data.userAttach.leader_num + "");
            User me = UserPreference.getUser();
            mFollow.setStatus(me.uid, data);
        }

        /**
         * 是否显示消息
         *
         * @param display
         */
        public void displayMessagePoint(Boolean display) {
            if (display) {
                mMessage.setCompoundDrawablesWithIntrinsicBounds(R.drawable.detail_message, 0, R.drawable.red_circle_num_point, 0);

            } else {
                mMessage.setCompoundDrawablesWithIntrinsicBounds(R.drawable.detail_message, 0, 0, 0);
            }

        }


        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.dfv_follow:
                    mFollow.doToggleAction();
                break;
                case R.id.tv_message:
                    displayMessagePoint(false);
                    listener.messageClick();
                    break;
                case R.id.tv_mysociety:
                    listener.mysocietyClick();
                    break;
                case R.id.tv_works_count:
                case R.id.ll_works:
                    listener.myworkClick();
                    break;
                case R.id.tv_follow_count:
                case R.id.ll_follow:
                    listener.myFollowClick();
                    break;
                case R.id.tv_fensi_count:
                case R.id.ll_fensi:
                    listener.myFensiClick();
                    break;
                default:
                    break;
            }
        }
    }

    /**
     * 跳转到关注页面
     */
    public void forwardFollow() {
        Intent intent = new Intent(getActivity(), AttentionListActivity.class);
        intent.putExtra("uid", user.uid);
        intent.putExtra("type", 0);
        startActivity(intent);
    }

    /**
     * 跳转到粉丝页面
     */
    public void forwardFensi() {
        Intent intent = new Intent(getActivity(), AttentionListActivity.class);
        intent.putExtra("type", 1);
        intent.putExtra("uid", user.uid);
        startActivity(intent);
    }

    /**
     * 跳转到我的消息页面
     */
    public void forwardMyMessage() {
        Intent intent = new Intent(this.getActivity(), MessageCenterActivity.class);
        startActivity(intent);
    }

    /**
     * 跳转到我的社团页面
     */
    public void forwardMySociety() {
        Intent intent = new Intent(getActivity(), MySocietyListActivity.class);
        intent.putExtra("uid", user.uid);
        startActivity(intent);
    }


    public interface DetailVideoListener {
        public void videoCardClick(VideoCard card);

    }

    public static class SocietyUserDynamicViewHolder extends BaseRecycleViewHolder<VideoCard> {
        //视频封面
        private NetworkImageView mVideoThum;
        //视频描述
        private TextView mVideoDesc;
        //点赞
        private TextView mZan;
        //评论
        private TextView mComment;
        private LinearLayout llcard;

        private View itemView;

        private int margin;
        Boolean isFirstLine = false;
        Boolean isFristRow = false;
        Boolean isSecondRow = false;
        Boolean isThridRow = false;

        private DetailVideoListener listener;

        public SocietyUserDynamicViewHolder(View itemView, DetailVideoListener listener) {
            this(itemView);
            margin = itemView.getResources().getDimensionPixelSize(R.dimen.dimen_3);
            this.listener = listener;
        }

        public void initWidget(View itemView) {
            this.itemView = itemView;
            llcard = (LinearLayout) itemView.findViewById(R.id.ll_card);
            mVideoThum = (NetworkImageView) itemView.findViewById(R.id.niv_video_thum);
            mVideoDesc = (TextView) itemView.findViewById(R.id.tv_video_desc);
            mZan = (TextView) itemView.findViewById(R.id.tv_zan);
            mComment = (TextView) itemView.findViewById(R.id.tv_comment);
        }

        public int getWidth() {
            int width = (ScreenUtils.getScreenW() - 6 * margin) / 3;
            return width;
        }

        public void checkPosition(int position) {
            //默认非第一行，非第一列
            if (position <= 2)
                isFirstLine = true;
            if (position % 3 == 0)
                isFristRow = true;
            else if (position % 3 == 1) {
                isSecondRow = true;
            } else if (position % 3 == 2) {
                isThridRow = true;
            }
        }

        public void resetMargin(int position) {
            int height = getWidth();
            int paddingtop = 0;
            int paddingbottom = 0;
            int paddingleft = 0;
            int paddingright = 0;
            if (isFirstLine) {
                paddingtop = 0;
                paddingbottom = 0;
            } else {
                paddingtop = 3 * margin;
                paddingbottom = 0;
            }
            if (isFristRow) {
                paddingleft = 0;
                paddingright = 2 * margin;
            } else if (isSecondRow) {
                paddingright = margin;
                paddingleft = margin;
            } else {
                paddingleft = 2 * margin;
                paddingright = 0;
            }
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(height, height);
            lp.setMargins(paddingleft, paddingtop, paddingright, paddingbottom);
            mVideoThum.setLayoutParams(lp);

        }


        public SocietyUserDynamicViewHolder(View itemView) {
            super(itemView);
            initWidget(itemView);
        }

        @Override
        public void renderView(final VideoCard data, int position) {
            checkPosition(position);
            resetMargin(position);
            mVideoThum.setImageUrl(data.video.thumUrl, HttpUtils.getImageLoader());
            mVideoDesc.setText(data.description);
            mZan.setText(data.videoAttach.praisenum + "");
            mComment.setText(data.videoAttach.replynum + "");
            this.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    listener.videoCardClick(data);
                }
            });

        }
    }


}
